import os
import time
import subprocess
from pathlib import Path

import pytest

from tinyops.library.config import ServerConfig
from tinyops.config import Config

from .demo_server import CONFIG_FILEPATH, DemoServer


# https://coverage.readthedocs.io/en/coverage-5.0.3/subprocess.html
os.environ['COVERAGE_PROCESS_START'] = str(Path('.coveragerc').absolute())


@pytest.fixture(scope="session")
def ssh_server() -> ServerConfig:
    server = ServerConfig(
        name='test-ssh-2222',
        host='127.0.0.1',
        port=2222,
        user='root',
        private_key='tests/etc/ssh/id_rsa',
        timeout=10,
    )
    start_command = ["bash", "tests/etc/ssh/start_ssh_container.sh"]
    stop_command = ["bash", "tests/etc/ssh/stop_ssh_container.sh"]
    subprocess.run(start_command, check=True, timeout=10)
    try:
        time.sleep(3)
        yield server
    finally:
        subprocess.run(stop_command, check=True, timeout=10)


@pytest.fixture(scope='session')
def demo_config() -> Config:
    config = Config.load(filepath=CONFIG_FILEPATH)
    return config


@pytest.fixture(scope='session')
def demo_server_internal() -> DemoServer:
    demo = DemoServer()
    try:
        demo.start()
        yield demo
    finally:
        demo.stop()


@pytest.fixture(scope="function")
def demo_server(demo_server_internal, ssh_server):
    demo_server_internal.wait_ready()
    yield demo_server_internal
